package com.tangding.service.user;

import java.util.Date;
import java.util.List;

import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tangding.common.exception.GException;
import com.tangding.common.tools.ErrorConstants;
import com.tangding.service.dao.user.UserRepository;
import com.tangding.service.entity.user.User;
import com.tangding.service.msg.request.user.CreateUserRequest;
import com.tangding.service.msg.request.user.UpdateUserRequest;

/**
 * @description 
 *
 * @author Ranger
 * @version 2017年11月9日_上午9:29:17
 *
 */
@Service
public class UserServiceImpl implements UserService{
	
	@Autowired
	UserRepository userRepository;

	@Override
	public User findUsersByUid(String username) throws GException {
		return userRepository.findUsersByUid(username);
	}

	@Override
	public void create(CreateUserRequest request) throws GException {
		User user = new User();
		user.setUid(request.getUid());
		user.setCreateTime(new Date());
		user.setEnableStart(request.getStart());
		user.setEnableEnd(request.getEnd());
		user.setEnable(true);
		user.setUserType((byte) 0);
		userRepository.save(user);
	}

	@Override
	public void actUser(boolean act, String uid, Date start, Date end) throws GException {
		User user = userRepository.findUsersByUid(uid);
		if (user == null) {
			throw new GException(ErrorConstants.USER_NOT_FOUND);
		}
		
		if (isRootAdmin(user)) {
			throw new GException(ErrorConstants.CANNOT_ACT_ROOT_ADMIN);
		}
		
		Document data = new Document();
		data.put("enable", act);
		if (start != null) {
			data.put("enableStart", start);
		}
		
		if (end != null) {
			data.put("enableEnd", end);
		}
		
		Document condition = new Document();
		condition.put("uid", uid);
		userRepository.updateDocument(data, condition);
	}

	@Override
	public void delete(String uid) throws GException {
		User user = userRepository.findUsersByUid(uid);
		if (user == null) {
			throw new GException(ErrorConstants.USER_NOT_FOUND);
		}
		if (isRootAdmin(user)) {
			throw new GException(ErrorConstants.CANNOT_DELETE_ROOT_ADMIN);
		}
		
		Document condition = new Document();
		condition.put("uid", uid);
		userRepository.delete(condition);
	}
	
	private boolean isRootAdmin(User user) {
		byte type = user.getUserType();
		if (type == 1) {//是超级管理员
			return true;
		}
		return false;
	}

	@Override
	public List<User> list() throws GException {
		return userRepository.findAll(new Document());
	}

	@Override
	public void update(UpdateUserRequest request) throws GException {
		Document condition = new Document();
		condition.put("uid", request.getUid());
		
		Document data = new Document();
		data.put("password", request.getPassword());
		data.put("name", request.getName());
		data.put("roles", request.getRoleIds());
		
		userRepository.updateDocument(data, condition);
	}
}
